<template>
	<view class="container">
		<view class="header-backgroud-box">
			<text class="header-backgroud-box-title">yzLinker</text>
			<text class="header-backgroud-box-content">基于ESP8266的通用控制器</text>
		</view>
		<uni-card title="设备面板" class="device-list-panel">
			<view class="device-no-content-tips" v-if="deviceList.length == 0?true:false"><text>请添加设备！</text></view>
			<uni-swipe-action class="device-list-box">
				<uni-swipe-action-item v-for="(item,index) in deviceList" :key="item.id" :right-options="item_options" @change="onListItemOptionChange($event,index)" @click="onListItemOptionClick($event,index)">
					<view class="content-box" @click="onListItemClick($event,index)">
						<view class="device-icon">
							<view class="image-box">
								<image :class="item.online?'active-image':'deactivate-image'" src="../../static/switch.png" mode="aspectFit"></image>
							</view>
							<text class="device-name">{{item.name}}</text>
						</view>
						<view class="device-info">
							<view class="id-line">
								<view class="content-id">ID：{{item.id}}</view>
								<view>{{item.online?'[ 在线 ]':'[ 离线 ]'}}</view>
							</view>
							<view>
								<text>类型：{{getSwitchTypeStr(item.type)}}</text>
							</view>
						</view>
					</view>
				</uni-swipe-action-item>
			</uni-swipe-action>
			<button class="device-add-btn" type="primary" @click="onAddDeviceBtn">添加设备</button>
		</uni-card>
		<view>
			<!-- 输入框示例 -->
			<uni-popup ref="inputDialog" type="dialog">
				<uni-popup-dialog ref="inputClose" mode="input" title="添加ESP8266设备" value="8f5e2300"
					placeholder="输入设备ID" @confirm="dialogInputConfirm"></uni-popup-dialog>
			</uni-popup>
		</view>
		<uni-card title="系统设置">
			<checkbox-group class="auto-login-checkbox" @change="onAutoLoginCheckChange">
				<checkbox :checked="autoLogin==true?true:false" value="autologin">自动登录</checkbox>
			</checkbox-group>
			<button class="exit-login-btn" @click="onExitLogin">退出登录</button>
		</uni-card>
	</view>
</template>

<script>
	import {
		commonData
	} from '@/utils/common.js'
	let tools = require('@/utils/tools');
	export default {
		data() {
			return {
				autoLogin:false,
				item_options: [{
						text: '删除',
						style: {
							backgroundColor: '#F56C6C'
						}
					}
				],
				deviceList:[],
			}
		},
		onLoad() {
			this.hide = false; //关闭Mqtt操作由于Hide显示产生，此时不边切换界面
			this.selected = false; //选择了具体的设备，用于控制退出状态
			
			this.readInfoLogin();
			this.readInfoDevice();
			
			// Mqtt连接与退出回调函数在此处注册
			commonData.mqtt.onConnect = ()=>{  //连接Mqtt服务器成功回调
				console.log('connect on device page.');
				this.initMqttMsg();
			}
			commonData.mqtt.onConnectFaild = (error)=>{ //连接Mqtt服务器失败回调
				console.log('connect mqtt server faild.',error)
				uni.showToast({
					title:'连接失败！',
					icon:'error'
				})
			}
			commonData.mqtt.onExit = ()=>{ //断开Mqtt服务器连接时的回调
				//在断开Mqtt服务器的时候，有3种情况导致此回调调用
				// 1.单击了退出登录按钮，对mqtt.close进行调用，关闭Mqtt时自动调用此函数。
				// 2.在OnHinde、OnShow中对Mqtt连接与断开进行了操作，如果产生了OnHinde动作，
				//    则会断开Mqtt连接，从而自动调用了此函数。
				// 3.在选择了具体设备进行操作时，由于要进行界面操作，需要关闭Mqtt，从而引发此函数调用。
				// 不同原因对应不同操作，要分开处理。
				
				if(!this.hide){
					//hide=false 则表示Mqtt退出不是由OnHide操作引起的。
					//此时需要区分是否选择了具体设备
					if(this.selected){//当前退出Mqtt原因为选择了具体设备
						uni.navigateTo({
							url:'/pages/control/control',
						})
						this.selected = false;
					}else{
						uni.redirectTo({
						url:'/pages/login/login',
						success() {
							console.log('back login page success.')
						},
						fail(e) {
							console.log('faild to back login page.'+JSON.stringify(e))
						}
						})
					}
				}
				this.hide = false;
			}
			
			if(commonData.mqtt.isConnected()){
				console.log('have connected.')
				this.initMqttMsg();
			}else{
				commonData.mqtt.login();
			}
			
			this.updateDeviceList();
		},
		onShow() {
			console.log('on show.')
			if(!commonData.mqtt.isConnected()){
				commonData.mqtt.login();
				this.updateDeviceList();
			}else{
				console.log('connected.')
			}
		},
		onHide() {
			console.log('on hide.')
			if(commonData.mqtt.isConnected()){
				commonData.mqtt.close();
				this.hide = true;
			}
		},
		methods: {
			/******************
			  UI相关功能代码
			******************/
			//设备面板界面单击具体设备列表项
			onListItemClick(e,index){
				console.log('list item '+index+' click!')
				commonData.curDevice = this.deviceList[index].id
				this.selected = true;
				commonData.mqtt.close();
				// uni.navigateTo({
				// 	url:'/pages/control/control',
				// })
			},
			onListItemOptionChange(e,index){
				console.log('change index:'+index);
				console.log('change event:'+e)
			},
			onListItemOptionClick(e,index){
				console.log('click index:'+index);
				console.log('click event:'+JSON.stringify(e))
				commonData.deviceList.splice(index,1);
				setTimeout(()=>{
					this.updateDeviceList()
				},500)
				
			},
			onAutoLoginCheckChange(e){
				console.log('change :'+e.detail.value)
				if(e.detail.value == 'autologin'){
					this.autoLogin = true;
				}else{
					this.autoLogin = false;
				}
				this.saveInfoLogin();
			},
			onExitLogin(){
				if(commonData.mqtt.isConnected()){
					commonData.mqtt.close()
				}else{
					console.log('back login page.')
					uni.redirectTo({
						url:'/pages/login/login',
						success() {
							console.log('back login page success.')
						},
						fail(e) {
							console.log('faild to back login page.'+JSON.stringify(e))
						}
					})
				}
			},
			readInfoLogin(){
				uni.getStorage({
					key:"esp8266_login",
					success:(res)=>{
						console.log('read user login info success.')
						let data = JSON.parse(res.data);
						this.userInput = data['username'];
						this.pwdInput = data['password'];
						this.rememberUser = data['remeberuser'];
						this.autoLogin = data['autologin']
						console.log('auto login:'+this.autoLogin)
					},
					fail:()=>{
						console.log('read user login info faild.')
					}
				})
			},
			saveInfoLogin(){
				uni.setStorage({
					key:"esp8266_login",
					data:JSON.stringify({
						'username':this.userInput,
						'password':this.pwdInput,
						'remeberuser':this.rememberUser,
						'autologin':this.autoLogin
						}),
					success:()=>{
						console.log('save user login info success.')
					},
					fail:()=>{
						console.log('save user login info faild.')
					}
				})
			},
			readInfoDevice(){
				uni.getStorage({
					key:"esp8266_device",
					success:(res)=>{
						commonData.deviceList = []
						console.log('read device login info success.')
						let save_data = JSON.parse(res.data);
						let data =save_data.data;
						//console.log(save_data)
						for(let i in data){
							let item = data[i];
							item.online = false;
							commonData.deviceList.push(item)
						}
					},
					fail:()=>{
						console.log('read device login info faild.')
					}
				})
			},
			saveInfoDevice(){
				let data = []
				for(let i in commonData.deviceList){
					let device_item = commonData.deviceList[i];
					let item = {
					'name':device_item.name,
					'id':device_item.id,
					'type':device_item.type
					}
					data.push(item);
				}
				uni.setStorage({
					key:"esp8266_device",
					data:JSON.stringify({'data':data}),
					success:()=>{
						console.log('save user device info success.')
					},
					fail:()=>{
						console.log('save user device info faild.')
					}
				})
			},
			getSwitchTypeStr(type){
				return tools.switchTypeStr(type);
			},
			
			/*----------------------------
			Mqtt连接成功后，对本页面需要的主题进行订阅，通过指定回调函数的方式一次性评阅
			----------------------------*/
			//初始化每个设备的Mqtt环境，对需要的主题进行订阅
			initMqttMsg(){
				//console.log(JSON.stringify(commonData.deviceList))
				for(let i in commonData.deviceList){
					let device_item = commonData.deviceList[i];
					this.initDeviceWithId(device_item.id);
				}
			},
			initDeviceWithId(deviceId){
				//在这里可以加入每个设备都需要订阅的主题
				commonData.mqtt.addTopic(deviceId,'online_re',this.onLineCallBack)
			},
			//onLineCallback
			onLineCallBack(id,topic,payload){
				console.log('on line device.')
				console.log('device id is:'+id);
				let device_index = tools.findIdInDeviceList(id,commonData)
				if(device_index == -1){
					return;
				}
				console.log('device index:'+device_index)
				let device = commonData.deviceList[device_index]
				let data = JSON.parse(payload);
				device.name = data.name;
				device.online = true;
				device.type = data.type;
				device.status = data.status;
				this.updateDeviceList();
				this.saveInfoDevice();
			},
			
			//commonData数据与当前界面交互
			updateDeviceList(){
				this.deviceList = []
				for(let i in commonData.deviceList){
					let device_item = commonData.deviceList[i];
					let show_item = device_item;
					this.deviceList.push(show_item)
				}
			},
			//添加设备部分
			inputDialogToggle() {
				this.$refs.inputDialog.open()
			},
			dialogInputConfirm(val) {
				console.log(val)
				this.$refs.inputDialog.close()
				//this.addDevice(val)
				let device_index = tools.findIdInDeviceList(val,commonData)
				if(device_index != -1){
					uni.showToast({
						title:"设备"+val+"已存在！"
					})
				}else{
					let item = {
					'name':'未知设备',
					'id':val,
					'online':false,
					'type':'未知'
					}
					commonData.deviceList.push(item);
					
					this.updateDeviceList();
					this.initDeviceWithId(val);

					commonData.mqtt.publishWithId(val,'online',JSON.stringify({msg:'hello esp.'}))
					this.saveInfoDevice();
				}
			},
			onAddDeviceBtn(evt){
				this.inputDialogToggle()
			}
			
		}
	}
</script>

<style lang="scss">
	.container {
		font-size: 28rpx;
		line-height: 48rpx;

		.header-backgroud-box{
			height: 300rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			background-color: white;
			//background-image: url('data:');
			background-size: 60%;
			background-repeat: no-repeat;
			background-position: 90% 0%;
			//border: solid 1rpx cyan;
			.header-backgroud-box-title{
				display: flex;
				margin-left: 50rpx;
				font-size: 2em;
				color: yellowgreen;
				line-height: 100rpx;
			}
			.header-backgroud-box-content{
				display: flex;
				margin-left: 50rpx;
				font-size: 32rpx;
				line-height: 50rpx;
				color: #77eeff;
			}
		}
		
		.device-list-panel{			
			.device-no-content-tips{
				margin: 30rpx;
				display: flex;
				flex-direction: row;
				justify-content: center;
			}
			
			.device-list-box{
				margin: 20rpx 10rpx;
				
				.content-box{
					margin: 10rpx 10rpx;
					border:solid 1rpx blue;
					border-radius: 20rpx;
					display: flex;
					flex-direction: row;
					
					.device-icon{
						//border: #77eeff solid 1px;
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: center;
						padding-right: 10rpx;
						width: 200rpx;
						height: 200rpx;
						.image-box{
							// width: 100rpx;
							// height: 50rpx;
							.active-image{
								width: 100rpx;
								height: 100rpx;
								margin: 10rpx 0rpx;
							}
							
							.deactivate-image{
								width: 100rpx;
								height: 100rpx;
								margin: 10rpx 0rpx;
								opacity: 0.4;
								filter: alpha(opactiy=40);
							}
						}
						.device-name{
							margin: 0rpx 0rpx;
							align-items: center;
						}
					}
					.device-info{
						//border: #55ff7f solid 1px;
						flex-grow: 1;
						display: flex;
						flex-direction: column;
						justify-content: center;
	
						.id-line{
							display: flex;
							flex-direction: row;
							justify-content: flex-start;
							.content-id{
								margin-right: 50rpx;
							}
						}
					}
				}
			}
			
			.device-add-btn{
				margin: 20rpx 30rpx;
			}	
		}
		
		.auto-login-checkbox{
			margin: 25rpx;
		}
		
		.exit-login-btn{
			margin: 35rpx;
		}
	}
</style>
